import {WarningOutlined} from '@ant-design/icons';
import {Component} from 'react';
import styles from "./index.module.scss"

interface EBProps {
    children: JSX.Element;
    fallback?: React.ReactNode;
}

interface EBState {
    hasError: boolean;
}

/**
 * 捕获子组件的异常，并降级UI展示
 * https://zh-hans.reactjs.org/docs/error-boundaries.html
 */
export default class SysErrorBoundary extends Component<EBProps, EBState> {
    constructor(props: EBProps) {
        super(props);
        this.state = {hasError: false};
    }

    static getDerivedStateFromError() {
        return {hasError: true};
    }

    componentDidCatch(error: any, errorInfo: any) {
        // 打印错误信息
        // 或者将错误日志上报给服务器
        console.log("我是错误日志", error, errorInfo);
    }

    render() {
        const {children, fallback} = this.props;
        if (!this.state.hasError) return children;
        return fallback ? (
            fallback
        ) : (
            <div className={styles.errorBoundary}>
                <WarningOutlined/>
                <div>加载出错,请刷新页面</div>
            </div>
        );
    }
}


const typeMap = {
    403: {
        // img: img403,
        title: '403',
        desc: '抱歉，你无权访问该页面',
    },
    404: {
        // img: img404,
        title: '404',
        desc: '很抱歉! 您访问的页面不存在，\n请稍后再试',
    },
    500: {
        // img: img500,
        title: '500',
        desc: '很抱歉! 您查找的页面渲染错误，\n请稍后再试',
    },
};

interface ExceptionProps {
    hideLogo?: boolean;
    type: keyof typeof typeMap;
    style?: React.CSSProperties;
}

export function Exception(props: ExceptionProps) {
    const { hideLogo = false, type, style } = props;
    const pageType = type in typeMap ? type : '404';
    const configObj = typeMap[pageType];

    return (
        <div className={styles.exception} style={style}>
            <div className={styles.content}>
                {hideLogo ? null : (
                    <div className={styles.sysname}>
                        {/*<img src={logoImg} alt="" />*/}
                    </div>
                )}
                <div className={styles.desc}>{configObj.desc}</div>
                <div className={styles.actions}></div>
            </div>
            <div className={styles.imgBlock}>
                {/*<div*/}
                {/*    className={styles.imgEle}*/}
                {/*    style={{ backgroundImage: `url(${configObj.img})` }}*/}
                {/*/>*/}
            </div>
        </div>
    );
}


// export function Page403() {
//     return (
//         <PageWrapper>
//             <Exception type={403} />
//         </PageWrapper>
//     );
// }
//
// export function Page404() {
//     return (
//         <PageWrapper>
//             <Exception type={404} />
//         </PageWrapper>
//     );
// }
//
// export function Page500() {
//     return (
//         <PageWrapper>
//             <Exception hideLogo type={500} />
//         </PageWrapper>
//     );
// }
